package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author gakki
 * @create 2022/5/4 17:05
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    UserService userService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrdersMapper ordersMapper;


    /**
     * 用户下单
     *
     * @param orders
     */
    @Transactional
    @Override
    public void submitOrder(Orders orders) {

        //A. 获得当前用户id, 查询当前用户的购物车数据，购物车不能为空
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lambdaQueryWrapper);

        //购物车不能为空
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new CustomException("购物车为空，无法下单！");
        }

        //B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);

        //C. 根据地址ID, 查询地址数据,地址不能为空
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("地址为空，无法下单！");
        }

        //工具类生成订单id
        long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

        //D. 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setImage(item.getImage());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetailList);

        //F. 删除当前用户的购物车列表数据
        shoppingCartService.remove(lambdaQueryWrapper);
    }

    /**
     * 再来一单
     * @param orders
     */
    @Transactional
    @Override
    public void oneMoreOrder(Orders orders){
        //根据id获取order对象
        Orders order = this.getById(orders);

        //使用订单工具生成订单号，并对order对象的id和number进行设置
        long orderID = IdWorker.getId();
        order.setId(orderID);
        order.setNumber(String.valueOf(orderID));
        //设置未派送状态
        order.setStatus(2);
        //更新order对象的下单和结账时间
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        //order对象保存至数据库
        this.save(order);

        //订单细节表，进行相关信息保存
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);
        List<OrderDetail> newOrderDetailList= orderDetailList.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail, "id");
            orderDetail.setOrderId(orderID);
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(newOrderDetailList);
    }

    /**
     * 统计月份订单数量
     * @return
     */
    @Override
    public List<Map> countBymonth() {
        return ordersMapper.countByMonth();
    }
}
